package com.itheima.reggie.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category>  implements CategoryService{
 @Autowired
 private DishService dishService;
 @Autowired
 private SetmealService setmealService;
 @Override
 public R<String> get(Category category) {
  this.save(category);
  return R.success("添加成功");
 }

 @Override
 public Page page(Integer page, Integer pageSize) {
  Page pageInfo = new Page(page,pageSize);
  LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
   qw.orderByAsc(Category::getSort);
   this.page(pageInfo,qw);
  return pageInfo;
 }

 @Override
 public R<String> delete(Long id) {
  LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
  LambdaQueryWrapper<Dish> dqw = qw.eq(Dish::getCategoryId, id);
//  LambdaQueryWrapper<Dish> dqw = Wrappers.<Dish>lambdaQuery().eq(Dish::getId, id);
  int count1 = dishService.count(dqw);
  if (count1>0){
  throw  new CustomException("当前分类下关联了菜品，不能删除");
  }
  LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = Wrappers.<Setmeal>lambdaQuery().eq(Setmeal::getCategoryId, id);
  int count2 = setmealService.count(lambdaQueryWrapper);
  if (count2>0){
   throw  new CustomException("当前分类下关联了套餐，不能删除");
  }
  this.removeById(id);
  return R.success("删除成功");
 }

 @Override
 public R<String> upDate(Category category) {
  this.updateById(category);
  return  R.success("修改成功");
 }

 @Override
 public R<List<Category>> list(Category category) {
  LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = Wrappers.<Category>lambdaQuery().
   eq(category.getType() != null, Category::getType, category.getType())
   .orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
  List<Category> list = this.list(categoryLambdaQueryWrapper);
  return  R.success(list);

 }
}
